package com.zx.model.log;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.zx.util.Assert;

/**
 * @Project: ngnix_analyze
 * @Title: LogIpStatModel
 * @Description: 日志分析-IP次数
 * @author: zhangxue
 * @date: 2018年8月2日上午12:11:18
 * @company: alibaba
 * @Copyright: Copyright (c) 2015
 * @version v1.0
 */
public class LogIp implements Comparable<LogIp>{
	
	/** 用户的IP */
	private String userIp;
	
	/** ip的访问次数 */
	private Integer count;
	
	public LogIp(String userIp, Integer count) {
		this.userIp = userIp;
		this.count = count;
	}

	/**
	 * 获得日志中对IP的分析
	 * @param list
	 * @return key=ip, value=次数
	 * @date: 2018年8月1日下午11:55:16
	 */
	public static List<LogIp> stat(List<LogMode> list){
		List<LogIp> result = new ArrayList<>();
		if(Assert.isEmpty(list)) {
			return result;
		}
		// 分类统计
		Map<String, LogIp> tempMap = new HashMap<>();
		for (LogMode logMode : list) {
			String userIp = logMode.getRemoteAddr();
			LogIp model = tempMap.get(userIp);
			if(model != null) {
				tempMap.get(userIp).setCount(model.getCount() + 1);
			} else {
				tempMap.put(userIp, new LogIp(userIp, 1));
			}
		}
		// 转为list
		for (Entry<String, LogIp> logIpStatModel : tempMap.entrySet()) {
			result.add(logIpStatModel.getValue());
		}
		// 排序，默认降序排序
		Collections.sort(result);
		return result;
	}
	
	
	public String getUserIp() {
		return userIp;
	}

	public void setUserIp(String userIp) {
		this.userIp = userIp;
	}

	public Integer getCount() {
		return count;
	}

	public void setCount(Integer count) {
		this.count = count;
	}

	@Override
	public String toString() {
		return "{'userIp':'" + userIp + "', 'count':" + count + "}";
	}

	@Override
	public int compareTo(LogIp o) {
		return ~this.getCount().compareTo(o.getCount());
	}
	
}
